import { sdkWkLpInfo, WkLpInfo } from "@@/sdk/web3Eth";
import { useInterval } from "@@/hooks/toolsHooks";
import useBalanceStore, { StoreCoinItem } from "@@/store/useBalanceStore";
import { parseAmount, parseBalance } from "@@/sdk/index";
import { divide } from "mathjs";

export { type WkLpInfo };
/**
 *
 * @param contract_addr 合约地址
 * @param updateTime
 * @returns
 */
export function useWkLpInfo(
  defaultParams: Parameters<typeof sdkWkLpInfo>,
  updateTime: number = 10 * 1000
) {
  const balanceStore = useBalanceStore();
  /**未处理的原数据 */
  const lpInfo_ = ref<WkLpInfo>();
  async function getWkLpInfo(...params: Parameters<typeof sdkWkLpInfo> | []) {
    if (params.length === 0) params = defaultParams;
    const res = await sdkWkLpInfo(...params);
    if (!res.status) return;
    lpInfo_.value = res.data;
    return res.data;
  }
  let close = () => {};
  /**lp矿池数据 */
  const lpInfo = computed<LpInfo | undefined>(() => {
    const wkc = balanceStore.getCoinByCode("wkc");
    const data_ = lpInfo_.value;
    if (!data_ || !wkc) return;
    const totalSupply = parseBalance(data_.lpTotalSupply, wkc.format);
    const balance = parseBalance(data_.lpBalance, wkc.format);
    return {
      totalSupply,
      balance,
      myRatio: divide(Number(balance), Number(totalSupply)),
      balance__: data_.lpBalance,
      totalSupply__: data_.lpTotalSupply,
    };
  });
  /**lp双币数据 */
  const lpCoinEnum = computed<AnyObject<LpCoin>>(() => {
    const wkc = balanceStore.getCoinByCode("wkc");
    const usdt = balanceStore.getCoinByCode("usdt");
    const data_ = lpInfo_.value;
    if (!wkc || !usdt || !data_) return {};
    return {
      [wkc.id]: {
        ...wkc,
        totalAmount__: data_.tokenAmount,
        balance__: data_.tokenBalance,
        totalAmount: parseBalance(data_.tokenAmount, wkc.format),
        balance: parseBalance(data_.tokenBalance, wkc.format),
        price: data_.tokenPrice,
      },
      [usdt.id]: {
        ...usdt,
        totalAmount__: data_.usdtAmount,
        balance__: data_.usdtBalance,
        totalAmount: parseBalance(data_.usdtAmount, usdt.format),
        balance: parseBalance(data_.usdtBalance, usdt.format),
        price: "1",
      },
    };
  });
  if (updateTime > 0) {
    getWkLpInfo();
    close = useInterval(() => getWkLpInfo(), updateTime).close;
  }
  return { lpInfo_, lpCoinEnum, lpInfo, getWkLpInfo, close };
}

export interface LpInfo {
  /**全网总lp量 */
  totalSupply: string;
  /**
   * ! 以'__'结束的是未处理精度的数据
   */
  totalSupply__: string;
  /**我的lp量 */
  balance: string;
  /**
   * ! 以'__'结束的是未处理精度的数据
   */
  balance__: string;
  /**我的lp量在全网的占比 */
  myRatio: number;
}

export interface LpCoin extends StoreCoinItem {
  /**全网lp总量中该币种的数量 */
  totalAmount: string;
  /**
   * ! 以'__'结束的是未处理精度的数据
   */
  totalAmount__: string;
  /**全网lp总量中该币种我的数量 */
  balance: string;
  /**
   * ! 以'__'结束的是未处理精度的数据
   */
  balance__: string;
  price: string;
}
